<?php
namespace App\Edu\Services;

use App\Edu\Models\EduCourseLessonModel;
use App\Edu\Models\EduCourseModel;
use App\Exceptions\ApiException;
use App\Services\CommonBaseService;

class EduCourseService extends CommonBaseService
{

    protected $eduCourseLessonModel;

    public function __construct(EduCourseModel $model, EduCourseLessonModel $eduCourseLessonModel)
    {
        $this->model = $model;
        $this->eduCourseLessonModel = $eduCourseLessonModel;
    }

    /** 
     * 列表
     */
    public function courseList($params)
    {
        $list = $this->model->getList($params, $this->getPageSize($params));
        return $list;
    }

    /** 
     * 保存
     */
    public function saveInfo($data)
    {
        if (!empty($data['course_id'])) {
            $info = $this->findOneById($data['course_id'], 'id');
            if (empty($info['id'])) {
                throw new ApiException(1000);
            }
        }
        $saveData = [
            'user_id' => $data['user_id'],
            'course_title' => $data['course_title'],
            'course_image' => $data['course_image'] ?? '',
            'video_image' => $data['video_image'] ?? '',
            'course_desc' => $data['course_desc'] ?? '',
            'course_time' => $data['course_time'] ?? 1,
            'course_sort' => $data['course_sort'] ?? 0,
        ];
        if (!empty($data['course_id'])) {
            $ret = $this->model->insertData($saveData);
        } else {
            $ret = $this->model->updateData($saveData, ['course_id' => $data['course_id']]);
        }
        return $ret;
    }

    /** 
     * 删除
     */
    public function deleteInfo($id)
    {
        return $this->delete($id);
    }

    /** 
     * 启用，禁用
     */
    public function changeCourseStatus($courseId)
    {
        $info = $this->findOneBy(['course_id' => $courseId], 'status');
        return $this->updateBy(['course_id' => $courseId], ['status' => $info['status'] == 1 ? 0 : 1]);
    }

    /** 
     * 课时
     */
    public function saveLessonInfo($data)
    {
        if (!empty($data['course_id'])) {
            $info = $this->findOneById($data['course_id'], 'id');
            if (empty($info['id'])) {
                throw new ApiException(1000);
            }
        }
        $saveData = [
            'course_id' => $data['course_id'],
            'parent_id' => $data['parent_id'] ?? '',
            'lesson_name' => $data['lesson_name'] ?? '',
            'lesson_url' => $data['lesson_url'] ?? ''
        ];
        if (!empty($data['lesson_id'])) {
            $ret = $this->eduCourseLessonModel->insertData($saveData);
        } else {
            $ret = $this->eduCourseLessonModel->updateData($saveData, ['lesson_id' => $data['lesson_id']]);
        }
        return $ret;
    }

    /** 
     * 删除课时
     */
    public function deleteLessonInfo($lessonId)
    {
        return $this->eduCourseLessonModel->deleteBy(['lesson_id' => $lessonId]);
    }

}
